package com.ssy.lingxi.dataauth.annotation.common;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.dataauth.handler.RedisServiceHolder;
import com.ssy.lingxi.dataauth.model.constant.DataAuthConstant;
import com.ssy.lingxi.dataauth.model.dto.DataAuthDto;
import com.ssy.lingxi.dataauth.utils.DataAuthUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 数据权限标记注解切点
 * @author 万宁
 * @version 2.0.0
 * @date 2021-03-31
 */
@Aspect
@Component
public class DataAuthFlagAspect {
    @Resource
    private HttpServletRequest request;

    @Pointcut("@annotation(com.ssy.lingxi.dataauth.annotation.common.DataAuthFlag)")
    public void serviceAspect() {
    }

    @Before("serviceAspect()")
    public void doBefore(JoinPoint joinPoint) {
        //Step 1:从HttpHeader中，找到当前请求的token、source、userId、Referer（并截取前端Url）
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        String source = request.getHeader("source");
        String authUrl = DataAuthUtil.findRequestPath(request.getHeader(DataAuthConstant.HTTP_HEADER_REFERER));

        if(!StringUtils.hasText(authUrl) || !StringUtils.hasText(token) || !StringUtils.hasText(source) || !StringUtils.hasText(userId)) {
            return;
        }

        //Step 2: 从Redis缓存中读取用户数据权限配置，如果没有数据权限配置，则返回的是Null
        String dataAuthKey = String.format(DataAuthConstant.DATA_AUTH_CACHE_KEY_FORMAT, token, userId, source);
        DataAuthDto dataAuthDto = (DataAuthDto) RedisServiceHolder.redisUtils.hGet(dataAuthKey, authUrl, Constants.REDIS_USER_INDEX);
        if(dataAuthDto != null) {
            request.setAttribute(DataAuthConstant.HTTP_ATTRIBUTE_ORDER_AUTH_FLAG, "1");
        }
    }
}
